import os

import time

import math

from FastFitsFileTools.FitsTools import Fits, Fitscut
from FastFitsFileTools.FitsTools.FitsMerge import FitsMerge
from FastFitsFileTools.FitsTools.FitsOutput import wirtreToFileForFast


def usage():
    print """

"-a", "file1:      [please give ***path/filename***]"
"-b", "file2:      [please give ***path/filename***]"
"-o", "output:    [output path]"

"""
name=[[]]
def readPath(filename,end):
    #nameS
    name[0].append(filename)
    while 1:
        files = filename.split('/')[len(filename.split('/')) - 1]

        filename2 = files[:len(files) - 9]+ str('%04d' % (int(files[len(files) - 9:len(files) - 5]) + 1))+'.fits'
        #print filename2
        filename2_path='/'
        for i in [x + 1 for x in range(filename.split('/').__len__() - 2)]:
            filename2_path+=(filename.split('/')[i]+'/')

        filename2=filename2_path+filename2
        print filename2
        if filename2!=end:
                        #os.path.exists(filename2) and os.path.getsize(filename2)>2000000000:
            name[0].append(filename2)
            filename=filename2
            #break;
        else:
            name[0].append(filename2)
            break;
            #readPath(filename)
    #name.append(nameS)
def getDepth(lastFilename):
    files = lastFilename.split('/')[len(lastFilename.split('/')) - 1]
    x=int(files[len(files) - 9:len(files) - 5])
    depth=math.log(x,2)
    return int(math.ceil(depth))
def getLength(lastFilename):
    files = lastFilename.split('/')[len(lastFilename.split('/')) - 1]
    x=int(files[len(files) - 9:len(files) - 5])
    return x
def exeMergeFits(filename1,filename2,outpath):
    return
    #fits1 = Fits(filename1)

    #fits2 = Fits(filename2)

    #fmerge = FitsMerge(fits1, fits2, 0, 0, 0)

    #fits_merged=fmerge.merge()

    wirtreToFileForFast(fits_merged,outpath)
def exeMutiMerage(firstname,lastFilename,outpath):
    readPath(firstname,lastFilename)
    d=getDepth(lastFilename)
    l=int(getLength(lastFilename))
    if os.path.exists('/home/zhangxiang/tmp/'):
        os.removedirs('/home/zhangxiang/tmp/')
    os.mkdir('/home/gpu/tmp/')
    tempoutpath='/home/gpu/tmp/'
    for i in range(d):
        name.append([])
        for j in range(0,name[i].__len__(),2):
            files=lastFilename.split('/')[len(lastFilename.split('/')) - 1]
            tempoutfullpath=tempoutpath+'tmp'+ files[:len(files) - 9]+str(i)+str(j)+".fits"
            name[i+1].append(tempoutfullpath)
            if l%2!=0:
                name[i + 1].append(name[i][j-1])
            if i==d-1:
                tempoutfullpath=outpath
          #  print i , j

            if j+1<name[i].__len__():
                print name[i][j], "and", name[i][j + 1]
                exeMergeFits(name[i][j], name[i][j+1], tempoutfullpath)

if __name__ == '__main__':
    import getopt, sys

    try:
        opts, args = getopt.getopt(sys.argv[1:], "a:b:o:",
                                   ["file1=", "file2=", "output="])

    except getopt.GetoptError:
        # print help information and exit:
        usage()
        sys.exit(2)
    if len(sys.argv) == 1:
        usage()
        sys.exit(2)
    for o, a in opts:
        if o in ("-h", "--help"):
            usage()
            sys.exit()
        if o in ("-a", "--file1"):
            filename1 = str(a)
        if o in ("-b", "--file2"):
            filename2 = str(a)
        if o in ("-o", "--output"):
            outpath = str(a)




    #exeMergeFits(filename1, filename2, outpath)
    exeMutiMerage(filename1, filename2,outpath)
